package org.zhucy.future;

import org.zhucy.design.factory.People;

import java.util.Date;
import java.util.concurrent.*;

public class FutureTest {

    private final ExecutorService executorService = Executors.newCachedThreadPool();


    public static void main(String[] args) {
        FutureTest futureTest = new FutureTest();
        futureTest.reader();
        futureTest.futureTask();
    }

    public void reader(){
        Callable<FutureModel> callable = ()-> {
            Thread.sleep(1);
            FutureModel futureModel = new FutureModel();
            futureModel.setId(1L);
            futureModel.setName("test ing");
            return futureModel;
        };
        Date d = new Date();
        Future<FutureModel> future = executorService.submit(callable);
        try {
            FutureModel _fm = future.get(5, TimeUnit.NANOSECONDS);
            System.out.println(_fm.getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            future.cancel(true);
            e.printStackTrace();
        }
    }

    public void futureTask(){
        FutureTask<FutureModel> futureTask = new FutureTask<>(()->{
            FutureModel futureModel = new FutureModel();
            futureModel.setName("FutureTask");
            return  futureModel;
        });
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
